package com.mlink.ai.chat.local.entity

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV


@Entity(tableName = "message_history", indices = [Index("message_id")])
data class ChatMessageEntity(
    @ColumnInfo(name = "message_title")
    val messageTitle: String,
    @ColumnInfo(name = "message_content")
    val messageContent: String,// 此条聊天记录 List<ChatItem> 的 json
    @ColumnInfo(name = "message_date")
    val date: String
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "message_id")
    var messageId: Long = 0


    companion object {
        // 用 MMKV 临时保存聊天界面的数据，杀应用后在 Splash 恢复
        private const val KEY_TEMP_MESSAGE_ENTITY = "key_temp_message_entity"
        private const val KEY_TEMP_PIC_LIST = "key_temp_pic_list"

        fun saveTempData(item: ChatMessageEntity?) {
            item ?: return
            MMKV.defaultMMKV().encode(KEY_TEMP_MESSAGE_ENTITY, Gson().toJson(item))
        }

        fun removeTempData() {
            MMKV.defaultMMKV().encode(KEY_TEMP_MESSAGE_ENTITY, "")
        }

        fun isHaveTempData(): Boolean {
            return !MMKV.defaultMMKV().decodeString(KEY_TEMP_MESSAGE_ENTITY).isNullOrEmpty()
        }

        fun getTempData(): ChatMessageEntity? {
            val json = MMKV.defaultMMKV().decodeString(KEY_TEMP_MESSAGE_ENTITY)
            if (json.isNullOrEmpty()) return null
            return Gson().fromJson(json, ChatMessageEntity::class.java)
        }

        fun saveTempPic(pathList: List<String>) {
            MMKV.defaultMMKV().encode(KEY_TEMP_PIC_LIST, Gson().toJson(pathList))
        }

        fun removeTempPic() {
            MMKV.defaultMMKV().encode(KEY_TEMP_PIC_LIST, "")
        }

        fun isHaveTempPic(): Boolean {
            return !MMKV.defaultMMKV().decodeString(KEY_TEMP_PIC_LIST).isNullOrEmpty()
        }

        fun getTempPic(): List<String> {
            val json = MMKV.defaultMMKV().decodeString(KEY_TEMP_PIC_LIST)
            if (json.isNullOrEmpty()) return listOf()
            val typeToken: TypeToken<List<String>> = object : TypeToken<List<String>>() {}
            return Gson().fromJson(json, typeToken.type)
        }
    }
}
